import cutils from '../../js/common/core-utils.js';

$(function() {
	$("#q-username").focus();

	var vars = cutils.getUrlVars();
	self.singleSelect = (cutils.getVars(vars, "singleSelect") == "true" ? true : false);

	initTable();

	$(document).keydown(function() {
		if (event.keyCode == 13) {
			doSearch();
		}
	});
});

self.initTable = function() {
	$('#data-table').datagrid({
		url: "/" + cutils.webApp + "/user/list?_time=" + cutils.now(),
		method: 'get',
		idField: "userId",
		animate: true,
		fit: true,
		fitColumns: false,
		pagination: true,
		pageSize: 50,
		pageList: [20, 50, 100, 200, 500],
		rownumbers: false,
		loadMsg: false,
		resizeHandle: 'both',
		checkOnSelect: true,
		selectOnCheck: true,
		emptyMsg: '无数据',
		singleSelect: self.singleSelect,
		onBeforeLoad: function(param) {
			param["pageNo"] = param.page;
			param["pageSize"] = param.rows;
			param["sortType"] = param.order;
			param["sortField"] = param.sort;
		},
		onLoadSuccess: function(data) {
			if (self.singleSelect) {
				$(".datagrid-header-check input").hide();
				$(".datagrid-header-check label").hide();
			}

			var vars = cutils.getUrlVars();
			var userId = cutils.getVars(vars, "userId");
			if (cutils.isEmpty(userId)) {
				return;
			}

			$.each(userId.split(","), function(i, node) {
				$('#data-table').datagrid("checkRow", $('#data-table').datagrid("getRowIndex", node));
			});
		},
		onLoadError: function() {
			$(".datagrid-body").html("<div style='width: 100%; height: 50px; line-height: 50px; text-align: center;font-size: 14px;'>数据加载出错</div>");
		},
		loadFilter: function(data, parentId) {
			return {
				total: data.data.count,
				rows: data.data.dataList
			};
		},
		columns: [[{
			field: 'ck',
			checkbox: true
		}, {
			field: 'username',
			title: '登录账号',
			width: 100,
			sortable: true
		}, {
			field: 'fullname',
			title: '姓名',
			width: 80,
			sortable: true
		}, {
			field: 'orgnames',
			title: '部门',
			width: 190,
			formatter: function(value, row, index) {
				return "<span title='" + value + "'>" + value + "</span>";
			}
		}, {
			field: 'rolenames',
			title: '角色',
			width: 190,
			formatter: function(value, row, index) {
				return "<span title='" + value + "'>" + value + "</span>";
			}
		}, {
			field: 'mobilenumber',
			title: '手机号码',
			width: 120
		}, {
			field: 'officephone',
			title: '办公电话',
			hidden: true,
			width: 120
		}, {
			field: 'email',
			title: '电子邮箱',
			width: 160
		}, {
			field: 'desc',
			title: '备注信息',
			width: 200,
			hidden: true
		}]]
	});
}

self.doSearch = function() {
	var queryParams = {};
	queryParams["username"] = $("#q-username").val();
	queryParams["fullname"] = $("#q-fullname").val();
	$('#data-table').datagrid('load', queryParams);
}

self.getChecked = function() {
	var rows = $('#data-table').datagrid('getChecked');
	if (self.singleSelect) {
		return rows == null ? null : rows[0];
	}
	return rows;
}